package com.hc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;



import com.hc.bean.RoleBean;
import com.hc.bean.SpeedTestResultBean;
import com.hc.service.SpeedTestService;
import com.hc.serviceImpl.SpeedTestServiceImpl;

public class SpeedTestServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
			
	String actionType = req.getParameter("actionType");  
		
	
	
	if("getTestResult".equals(actionType)){
		HttpSession session = req.getSession();  
	
		RoleBean bean = (RoleBean) session.getAttribute("roleBean");
		SpeedTestService service = new SpeedTestServiceImpl();
		
		String rateMax = req.getParameter("rateMax");  
		
		if(rateMax!=null&&bean!=null){
			
			SpeedTestResultBean resultBean= 	service.getSpeedTestResult(Double.parseDouble(rateMax), bean);
			
			if(resultBean==null){
				
				return;
			}
			
			JSONObject json = JSONObject.fromObject(resultBean);
			String msg = json.toString();
			returnMsg(req, resp, msg);
			
		}
	}
	
}


@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

private void returnMsg(HttpServletRequest req, HttpServletResponse resp,String msg) {
	
	resp.setCharacterEncoding("utf-8");
//	resp.setHeader("Content-type", "text/html;charset=UTF-8");
	PrintWriter w;
	try {
		w = resp.getWriter();
		w.write(msg);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}
}
